package cn.factorybox.utils;

import cn.factorybox.entity.UserInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

import java.lang.reflect.Field;
import java.security.PrivateKey;
import java.security.PublicKey;

public class JwtUtils {

    /**
     * 私钥加密token
     *
     * @param userInfo      载荷中的数据
     * @param key    私钥
     * @param expireMinutes 过期时间，单位秒
     * @return
     * @throws Exception
     */
    public static String generateToken(UserInfo userInfo, String key, int expireMinutes) throws Exception {
        return Jwts.builder()
                .claim(JwtConstants.JWT_KEY_ID, userInfo.getId())
                .claim(JwtConstants.JWT_KEY_USER_NAME, userInfo.getUsername())
                .claim(JwtConstants.JWT_KEY_PHONE, userInfo.getPhone())
                .claim(JwtConstants.JWT_KEY_EMAIL, userInfo.getEmail())
                .claim(JwtConstants.JWT_KEY_ROLES, userInfo.getRoles())
                .claim(JwtConstants.JWT_KEY_COMPANY_ID,userInfo.getCompanyId())
                .setExpiration(DateTime.now().plusMinutes(expireMinutes).toDate())
                .signWith(SignatureAlgorithm.HS256, key)
                .compact();
    }

    /**
     * 公钥解析token
     *
     * @param token     用户请求中的token
     * @param key 密钥
     * @return
     * @throws Exception
     */
    private static Jws<Claims> parserToken(String token, String key) {
        return Jwts.parser().setSigningKey(key).parseClaimsJws(token);
    }

    /**
     * 获取token中的用户信息
     *
     * @param token     用户请求中的令牌
     * @param key 密钥
     * @return 用户信息
     * @throws Exception
     */
    public static UserInfo getInfoFromToken(String token, String key) throws Exception {
        Jws<Claims> claimsJws = parserToken(token, key);
        Claims body = claimsJws.getBody();
        return new UserInfo(
                ObjectUtils.toString(body.get(JwtConstants.JWT_KEY_ID)),
                ObjectUtils.toString(body.get(JwtConstants.JWT_KEY_USER_NAME)),
                ObjectUtils.toString(body.get(JwtConstants.JWT_KEY_PHONE)),
                ObjectUtils.toString(body.get(JwtConstants.JWT_KEY_EMAIL)),
                ObjectUtils.toList(body.get(JwtConstants.JWT_KEY_ROLES)),
                ObjectUtils.toString(body.get(JwtConstants.JWT_KEY_COMPANY_ID))
        );
    }

    public static boolean checkObjFieldIsNotNull(Object obj) {   // true 不为空  false 为空
        boolean flag = false;
        try {
            for (Field f : obj.getClass().getDeclaredFields()) {
                f.setAccessible(true);
                if (f.get(obj) == null || f.get(obj) == "") {
                } else {
                    flag = true;
                }
            }
        } catch (Exception e) {
            return false;
        }
        return flag;
    }
}